package com.wolf.etl.core.handler;

import com.alibaba.fastjson.JSONObject;
import com.wolf.etl.model.EtlJavascriptModel;
import com.wolf.etl.model.EtlJavascriptParamModel;
import com.wolf.exception.ETL_ERROR_MSG;
import com.wolf.exception.WolfException;
import com.wolf.util.JavascriptUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

/**
 * javascript处理
 * <p>
 * 检查函数合法性  语法 返回结果
 *
 * @author sdyang
 * @date 2019/11/23 11:26
 **/
public class JavascriptHandler extends AbstractHandler {

    private static Logger logger = LoggerFactory.getLogger(JavascriptHandler.class);

    @Override
    public JSONObject done(JSONObject data) {
        logger.info("javascript handler");

        if (handler_id == null) {
            WolfException.report(ETL_ERROR_MSG.ERROR_TRANSFORM_RULE_008, "javascript id is null");
        }

        EtlJavascriptModel etlJavascript = manager.findJavascriptById(handler_id);

        List<EtlJavascriptParamModel> params = manager.findJavascriptParams(handler_id);

        if (etlJavascript == null) {
            WolfException.report(ETL_ERROR_MSG.ERROR_TRANSFORM_RULE_008, String.format("找不到javascript id:{}", handler_id));
        }

        // 拼接函数变量
        String functionVars = null;
        StringBuffer vars = new StringBuffer();
        for (EtlJavascriptParamModel p : params) {
            vars.append(p.getParam()).append(",");
        }
        if (vars.length() > 0) {
            functionVars = vars.substring(0, vars.length() - 1);
        }

        // 检查函数语法是否合法
        String content = String.format("function %s(%s){%s}", etlJavascript.getCode(), functionVars, etlJavascript.getContent());

        boolean legal = JavascriptUtil.check(String.format("%s.js", etlJavascript.getCode()), content);
        if (!legal) {
            WolfException.report(ETL_ERROR_MSG.ERROR_TRANSFORM_RULE_005, "javascript语法错误");
        }

        // 取出变量
        List<Object> args = new ArrayList<Object>();
        args = (List<Object>) data.get("data");

        // 执行，检查返回结果是否是JSONObject
        Object result = JavascriptUtil.exec(etlJavascript.getCode(), content, args);

        if (result == null) {
            WolfException.report(ETL_ERROR_MSG.ERROR_ELEMENT_003, "javascript执行结果为null");
        }

        JSONObject object = new JSONObject();
        object.put("data",result);

        if (Objects.isNull(handler)) {
            return object;
        }

        return this.handler.done(object);
    }

}
